

package com.zdsx.controller;

import com.zdsx.annotation.Login;
import com.zdsx.common.utils.Result;
import com.zdsx.common.validator.ValidatorUtils;
import com.zdsx.dto.BindPhoneDTO;
import com.zdsx.dto.SendSmsDTO;
import com.zdsx.dto.WxLoginDTO;
import com.zdsx.entity.UserEntity;
import com.zdsx.service.TokenService;
import com.zdsx.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 *
 * @author Lr
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wx")
@Api(tags = "wx相关登陆接口")
public class WxSysController {

    private final UserService userService;

    private final TokenService tokenService;

    /**
     * 登陆或注册
     * @param dto
     * @return
     */
    @PostMapping("login")
    @ApiOperation("登录接口")
    public Result<Map<String, Object>> login(@RequestBody WxLoginDTO dto) {
        //表单校验
        ValidatorUtils.validateEntity(dto);
        //用户登录
        Map<String, Object> map = userService.wxLogin(dto);
        return new Result().ok(map);
    }

    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(@ApiIgnore @RequestAttribute("userId") Long userId) {
        tokenService.expireToken(userId);
        return new Result();
    }


    // 发送绑定手机号码的验证码
    @Login
    @PostMapping("sendBindVerifySms")
    @ApiOperation("发送验证码接口，测试环境固定是123456")
    public Result sendBindSms(@RequestAttribute("userId") Long userId, @Valid @RequestBody SendSmsDTO mobile) {
        ValidatorUtils.validateEntity(mobile);
        userService.sendVerifySms(userId, mobile.getMobile(), "bind");
        return new Result();
    }

    // openid 绑定手机号码
    @Login
    @PostMapping("bindPhone")
    @ApiOperation("绑定手机号码")
    public Result bindingPhone(@RequestAttribute("userId") Long userId, @Validated @RequestBody BindPhoneDTO dto) {
        ValidatorUtils.validateEntity(dto);
        userService.bindPhone(userId, dto);
        return new Result();
    }

    @Login
    @PostMapping("isAdmin")
    @ApiOperation("判断是否管理员")
    public Result isMaster(@RequestAttribute("userId") Long userId) {
        String role = userService.getUserRole(userId);
        Map<String, String> map = new HashMap<>();
//        map.put("admin", is);
        map.put("role", role);
        return new Result().ok(map);
    }

    @Login
    @PostMapping("userInfo")
    @ApiOperation("用户信息")
    public Result userInfo(@ApiIgnore @RequestAttribute("userId") Long userId) {
        UserEntity user = userService.getUserByUserId(userId);
        return new Result().ok(user);
    }

}